<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-page-header @back="goBack" content="任务安排详情 - 已执行" />
      </div>
      <div class="header-actions">
        <el-button type="info" @click="goBack">
          <i class="el-icon-back"></i>返回
        </el-button>
      </div>
    </div>

    <!-- 基本信息卡片 -->
    <el-card class="info-card basic-info-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <i class="el-icon-user-solid card-icon"></i>老人基本信息
          </span>
        </div>
      </template>
      <div class="basic-info-content">
        <!-- 头像区域 -->
        <div class="avatar-section">
          <div class="avatar-container">
            <img 
              :src="getAvatarUrl(detailData.photo || detailData.elderly_photo)" 
              :alt="detailData.elderly_name || detailData.name || '老人头像'" 
              class="elderly-avatar"
              @error="handleImageError"
            />
          </div>
          <div class="elderly-info">
            <div class="elderly-name">{{ detailData.elderly_name || detailData.name || '未知' }}</div>
            <div class="elderly-tags">
              <el-tag size="small" :type="getGenderStyle(detailData.gender)">
                {{ detailData.gender || '未知' }}
              </el-tag>
              <el-tag size="small" type="info">{{ detailData.age || '未知' }}岁</el-tag>
            </div>
          </div>
        </div>
        
        <!-- 信息列表 -->
        <div class="info-grid">
          <div class="info-item">
            <label class="info-label">床位号：</label>
            <span class="info-value">{{ detailData.bed_no || '未分配' }}</span>
          </div>
          <div class="info-item">
            <label class="info-label">护理等级：</label>
            <span class="info-value level-badge">{{ detailData.nursing_level_name || '未知' }}</span>
          </div>
          <div class="info-item">
            <label class="info-label">联系电话：</label>
            <span class="info-value phone">{{ detailData.phone || detailData.contact || '未填写' }}</span>
          </div>
          <div class="info-item">
            <label class="info-label">入住时间：</label>
            <span class="info-value">{{ parseTime(detailData.check_in_time) || '未填写' }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 护理项目信息卡片 -->
    <el-card class="info-card project-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <i class="el-icon-document card-icon"></i>护理项目信息
          </span>
        </div>
      </template>
      <div class="project-content">
        <!-- 项目标题区域 -->
        <div class="project-header">
          <div class="project-main">
            <h3 class="project-name">{{ detailData.nursing_item_name || detailData.project_name || '未设置' }}</h3>
            <div class="project-meta">
              <span class="creator">创建人：{{ detailData.creator_name || '未知' }}</span>
              <span class="order-no">关联单据：{{ detailData.order_no || '无' }}</span>
            </div>
          </div>
          <div class="project-status">
            <el-tag :type="getProjectTypeStyle(detailData.project_type)" size="medium" effect="dark">
              {{ detailData.project_type || '未设置' }}
            </el-tag>
            <el-tag type="success" size="medium" effect="light">
              已执行
            </el-tag>
          </div>
        </div>

        <!-- 详细信息区域 -->
        <div class="project-details">
          <div class="detail-section">
            <h4 class="section-title">服务信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <label class="detail-label">期望服务时间：</label>
                <span class="detail-value">{{ parseTime(detailData.expected_service_time) || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <label class="detail-label">创建时间：</label>
                <span class="detail-value">{{ parseTime(detailData.create_time) || '未设置' }}</span>
              </div>
              <div class="detail-item">
                <label class="detail-label">项目类型：</label>
                <span class="detail-value">{{ detailData.project_type || '未知' }}</span>
              </div>
              <div class="detail-item">
                <label class="detail-label">护理员：</label>
                <span class="detail-value">{{ detailData.executor_name || '未知' }}</span>
              </div>
            </div>
          </div>

          <div class="detail-section">
            <h4 class="section-title">备注信息</h4>
            <div class="remark-content">
              <p>{{ detailData.order_remark || detailData.remark || detailData.note || detailData.memo || '无备注信息' }}</p>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 执行记录卡片 -->
    <el-card class="info-card execution-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="card-title">
            <i class="el-icon-finished card-icon"></i>执行记录
          </span>
        </div>
      </template>
      <div class="execution-content">
        <div class="execution-header">
          <div class="execution-main">
            <h3 class="execution-title">任务执行完成</h3>
            <div class="execution-meta">
              <span class="executor">执行人：{{ detailData.executor_name || '未知' }}</span>
              <span class="execution-status">执行结果：已完成</span>
            </div>
          </div>
          <div class="execution-time">
            <el-tag type="success" size="medium" effect="dark">
              <i class="el-icon-time"></i>
              {{ parseTime(detailData.execution_time) || '未知' }}
            </el-tag>
          </div>
        </div>

        <div class="execution-details">
          <div class="execution-section">
            <h4 class="section-title">执行详情</h4>
            <div class="execution-grid">
              <div class="execution-item">
                <label class="execution-label">执行人：</label>
                <span class="execution-value">{{ detailData.executor_name || (detailData.project_type === '护理计划内' ? '系统' : '未知') }}</span>
              </div>
              <div class="execution-item">
                <label class="execution-label">执行时间：</label>
                <span class="execution-value time-highlight">{{ parseTime(detailData.execution_time) || '未知' }}</span>
              </div>
              <div class="execution-item">
                <label class="execution-label">执行状态：</label>
                <span class="execution-value">
                  <el-tag type="success" size="small">已执行</el-tag>
                </span>
              </div>
              <div class="execution-item">
                <label class="execution-label">执行结果：</label>
                <span class="execution-value">
                  <el-tag type="success" size="small">已完成</el-tag>
                </span>
              </div>
            </div>
          </div>

          <div class="execution-section" v-if="detailData.execution_record || detailData.remark">
            <h4 class="section-title">执行记录</h4>
            <div class="record-content">
              <p>{{ detailData.execution_record || detailData.remark || '无执行记录' }}</p>
            </div>
          </div>

          <!-- 执行照片 -->
          <div class="execution-section" v-if="detailData.execution_image">
            <h4 class="section-title">
              <i class="el-icon-picture-outline"></i> 执行照片
            </h4>
            <div class="execution-images">
              <el-image
                v-for="(img, index) in parseImages(detailData.execution_image)"
                :key="index"
                :src="img"
                :preview-src-list="parseImages(detailData.execution_image)"
                :initial-index="index"
                fit="cover"
                class="execution-image-item"
              >
                <template #error>
                  <div class="image-error">
                    <i class="el-icon-picture-outline"></i>
                    <span>加载失败</span>
                  </div>
                </template>
              </el-image>
            </div>
          </div>

          <div class="execution-section" v-if="detailData.cancel_reason">
            <h4 class="section-title">取消信息</h4>
            <div class="cancel-content">
              <div class="cancel-item">
                <label>取消原因：</label>
                <span>{{ detailData.cancel_reason || '无' }}</span>
              </div>
              <div class="cancel-item">
                <label>取消时间：</label>
                <span>{{ parseTime(detailData.cancel_time) || '未知' }}</span>
              </div>
              <div class="cancel-item">
                <label>取消人：</label>
                <span>{{ detailData.cancel_person || '未知' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 加载状态 -->
    <el-skeleton v-if="loading" :rows="6" animated />
  </div>
</template>

<script setup name="ArrangementDetailExecuted">
import { ref, onMounted, getCurrentInstance } from 'vue'
import { getArrangementDetail } from "@/api/system/arrangement"
import { parseTime as ruoyiParseTime } from "@/utils/ruoyi"
import { useRoute, useRouter } from 'vue-router'

const { proxy } = getCurrentInstance()
const route = useRoute()
const router = useRouter()

const detailData = ref({})
const loading = ref(false)

/** 获取任务详情 */
function getDetail() {
  loading.value = true
  const id = route.query.id
  if (!id) {
    proxy.$modal.msgError("缺少任务ID")
    loading.value = false
    return
  }
  
  console.log('开始获取任务详情，ID:', id)
  
  getArrangementDetail(id).then(response => {
    console.log('详情API响应:', response)
    if (response.code === 200) {
      const data = response.data
      console.log('响应数据类型:', typeof data, '是否为数组:', Array.isArray(data))
      console.log('响应数据内容:', data)
      
      // 后端已去除 @MapKey("id")，现在直接返回 Map<String, Object>
      // data 就是一个普通的对象，直接赋值即可
      detailData.value = data || {}
      
      console.log('最终的详情数据:', detailData.value)
      console.log('所有字段列表:', Object.keys(detailData.value))
      console.log('护理员信息 executor_name:', detailData.value.executor_name)
      console.log('执行人ID executor:', detailData.value.executor)
      console.log('老人姓名 elderly_name:', detailData.value.elderly_name)
      console.log('护理项目名 nursing_item_name:', detailData.value.nursing_item_name)
      console.log('订单号 order_no:', detailData.value.order_no)
    } else {
      proxy.$modal.msgError(response.msg || "获取详情失败")
      console.error('API返回错误:', response)
    }
    loading.value = false
  }).catch(error => {
    console.error('获取任务详情失败:', error)
    loading.value = false
    proxy.$modal.msgError("获取详情失败: " + (error.message || '未知错误'))
  })
}

/** 返回上一页 */
function goBack() {
  router.go(-1)
}

/** 根据性别获取标签样式 */
function getGenderStyle(gender) {
  return gender === '男' ? 'primary' : 'danger'
}

/** 根据项目类型获取标签样式 */
function getProjectTypeStyle(projectType) {
  const typeMap = {
    '日常护理': 'success',
    '医疗护理': 'danger',
    '康复护理': 'warning',
    '心理护理': 'info',
    '护理计划内': 'primary',
    '临时护理': 'warning'
  }
  return typeMap[projectType] || 'info'
}

/** 时间格式化函数 */
function parseTime(time, format = '{y}-{m}-{d} {h}:{i}:{s}') {
  if (!time) return ''
  return ruoyiParseTime(time, format)
}

/** 解析执行照片 */
function parseImages(imageStr) {
  if (!imageStr) return []
  
  // 如果是逗号分隔的字符串,分割成数组
  const imageArray = typeof imageStr === 'string' 
    ? imageStr.split(',').map(img => img.trim()).filter(img => img) 
    : []
  
  // 为每个图片路径添加完整URL
  return imageArray.map(img => {
    // 如果已经是完整URL,直接返回
    if (/^https?:\/\//i.test(img)) return img
    // 如果是Windows路径,直接返回
    if (/^[a-zA-Z]:\\\\/.test(img) || img.includes('\\')) return img
    // 如果以/开头,直接返回
    if (img.startsWith('/')) return img
    // 否则加上/static/uploads/前缀
    return `/static/uploads/${img}`
  })
}

/** 获取头像URL */
function getAvatarUrl(photoName) {
  if (!photoName) return '/src/assets/images/profile.jpg'
  if (/^https?:\/\//i.test(photoName)) return photoName
  if (/^[a-zA-Z]:\\\\/.test(photoName) || photoName.includes('\\')) {
    return photoName
  }
  if (photoName.startsWith('/')) return photoName
  return `/static/uploads/${photoName}`
}

/** 头像加载失败处理 */
function handleImageError(event) {
  event.target.src = '/src/assets/images/profile.jpg'
}

onMounted(() => {
  getDetail()
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 50px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  
  .header-left {
    flex: 1;
  }
  
  .header-actions {
    display: flex;
    gap: 12px;
    
    .el-button {
      border-radius: 8px;
      padding: 10px 20px;
      font-weight: 500;
      
      i {
        margin-right: 6px;
      }
    }
  }
}

.info-card {
  margin-bottom: 24px;
  border: none;
  border-radius: 12px;
  overflow: hidden;
  
  &:hover {
    transform: translateY(-2px);
    transition: all 0.3s ease;
  }
}

.card-header {
  padding: 16px 24px;
  background: linear-gradient(90deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #e8e8e8;
  
  .card-title {
    font-size: 18px;
    font-weight: 600;
    color: #2c3e50;
    display: flex;
    align-items: center;
    
    .card-icon {
      margin-right: 8px;
      color: #409eff;
    }
  }
}

/* 基本信息卡片样式 */
.basic-info-card {
  .basic-info-content {
    display: flex;
    padding: 24px;
    gap: 40px;
    align-items: flex-start;
  }
  
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    min-width: 160px;
    
    .avatar-container {
      width: 100px;
      height: 100px;
      border-radius: 50%;
      overflow: hidden;
      border: 4px solid #e6f7ff;
      margin-bottom: 16px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      
      .elderly-avatar {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .elderly-info {
      text-align: center;
      
      .elderly-name {
        font-size: 20px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 8px;
      }
      
      .elderly-tags {
        display: flex;
        gap: 8px;
        justify-content: center;
      }
    }
  }
  
  .info-grid {
    flex: 1;
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 20px;
    
    .info-item {
      display: flex;
      align-items: center;
      padding: 12px 16px;
      background: #f8f9fa;
      border-radius: 8px;
      border-left: 4px solid #409eff;
      
      .info-label {
        width: 80px;
        color: #666;
        font-weight: 500;
        margin-right: 12px;
      }
      
      .info-value {
        color: #2c3e50;
        font-size: 14px;
        font-weight: 500;
        
        &.level-badge {
          background: #409eff;
          color: white;
          padding: 4px 12px;
          border-radius: 12px;
          font-size: 12px;
        }
        
        &.phone {
          color: #1890ff;
          font-weight: 600;
        }
      }
    }
  }
}

/* 护理项目卡片样式 */
.project-card {
  border-left: 6px solid #67c23a;
  
  .project-content {
    padding: 0;
  }
  
  .project-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 24px;
    background: linear-gradient(135deg, #f0f9ff 0%, #e6f7ff 100%);
    border-bottom: 1px solid #e8f4ff;
    
    .project-main {
      flex: 1;
      
      .project-name {
        font-size: 22px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 12px;
      }
      
      .project-meta {
        display: flex;
        gap: 30px;
        color: #666;
        font-size: 14px;
        
        .creator, .order-no {
          padding: 6px 12px;
          background: white;
          border-radius: 6px;
          border: 1px solid #e8e8e8;
        }
      }
    }
    
    .project-status {
      display: flex;
      flex-direction: column;
      gap: 8px;
      align-items: flex-end;
    }
  }
  
  .project-details {
    padding: 24px;
    
    .detail-section {
      margin-bottom: 24px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 16px;
        padding-bottom: 8px;
        border-bottom: 2px solid #f0f0f0;
      }
      
      .detail-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 20px;
        
        .detail-item {
          display: flex;
          flex-direction: column;
          padding: 16px;
          background: #f8f9fa;
          border-radius: 8px;
          border-left: 4px solid #67c23a;
          
          .detail-label {
            color: #666;
            font-size: 12px;
            margin-bottom: 6px;
            font-weight: 500;
          }
          
          .detail-value {
            color: #2c3e50;
            font-size: 14px;
            font-weight: 600;
          }
        }
      }
      
      .remark-content {
        padding: 16px;
        background: #f8f9fa;
        border-radius: 8px;
        border-left: 4px solid #909399;
        
        p {
          margin: 0;
          color: #666;
          line-height: 1.6;
          font-size: 14px;
        }
      }
    }
  }
}

/* 执行记录卡片样式 */
.execution-card {
  border-left: 6px solid #67c23a;
  
  .execution-content {
    padding: 0;
  }
  
  .execution-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 24px;
    background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
    border-bottom: 1px solid #b7eb8f;
    
    .execution-main {
      flex: 1;
      
      .execution-title {
        font-size: 22px;
        font-weight: 600;
        color: #52c41a;
        margin-bottom: 12px;
      }
      
      .execution-meta {
        display: flex;
        gap: 30px;
        color: #666;
        font-size: 14px;
        
        .executor, .execution-status {
          padding: 6px 12px;
          background: white;
          border-radius: 6px;
          border: 1px solid #b7eb8f;
        }
      }
    }
    
    .execution-time {
      .el-tag {
        font-size: 14px;
        font-weight: 600;
        
        i {
          margin-right: 4px;
        }
      }
    }
  }
  
  .execution-details {
    padding: 24px;
    
    .execution-section {
      margin-bottom: 24px;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #2c3e50;
        margin-bottom: 16px;
        padding-bottom: 8px;
        border-bottom: 2px solid #f0f0f0;
      }
      
      .execution-grid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 20px;
        
        .execution-item {
          display: flex;
          flex-direction: column;
          padding: 16px;
          background: #f6ffed;
          border-radius: 8px;
          border-left: 4px solid #52c41a;
          
          .execution-label {
            color: #666;
            font-size: 12px;
            margin-bottom: 6px;
            font-weight: 500;
          }
          
          .execution-value {
            color: #2c3e50;
            font-size: 14px;
            font-weight: 600;
            
            &.time-highlight {
              color: #52c41a;
              font-size: 15px;
              font-weight: 700;
            }
          }
        }
      }
      
      .record-content, .cancel-content {
        padding: 16px;
        background: #f8f9fa;
        border-radius: 8px;
        border-left: 4px solid #909399;
        
        p {
          margin: 0;
          color: #666;
          line-height: 1.6;
          font-size: 14px;
        }
        
        .cancel-item {
          display: flex;
          margin-bottom: 8px;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          label {
            width: 80px;
            color: #666;
            font-weight: 500;
            margin-right: 12px;
          }
          
          span {
            color: #2c3e50;
            flex: 1;
          }
        }
      }
      
      .execution-images {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
        gap: 16px;
        padding: 16px;
        background: #f8f9fa;
        border-radius: 8px;
        
        .execution-image-item {
          width: 100%;
          height: 150px;
          border-radius: 8px;
          overflow: hidden;
          cursor: pointer;
          transition: all 0.3s ease;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
          
          &:hover {
            transform: translateY(-4px);
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
          }
          
          :deep(.el-image__inner) {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
          
          .image-error {
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 100%;
            background: #f5f5f5;
            color: #999;
            
            i {
              font-size: 32px;
              margin-bottom: 8px;
            }
            
            span {
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 12px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
    
    .header-actions {
      flex-wrap: wrap;
      justify-content: center;
    }
  }
  
  .basic-info-content {
    flex-direction: column;
    gap: 24px !important;
  }
  
  .info-grid, .detail-grid, .execution-grid {
    grid-template-columns: 1fr !important;
    gap: 12px !important;
  }
  
  .project-header, .execution-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
    
    .project-status, .execution-time {
      align-items: center !important;
      flex-direction: row !important;
      justify-content: center;
    }
  }
  
  .project-meta, .execution-meta {
    flex-direction: column;
    gap: 8px !important;
  }
}
</style>